<?php

// 数据库连接配置
$host = '127.0.0.1';
$db   = 'web_tb';
$user = 'root';
$pass = 'root';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

// 定义表名变量
$table = 'info';

// 处理 POST 请求，将接收到的数据写入数据库
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 读取 POST 数据
    $postData = file_get_contents('php://input');
    $data = json_decode($postData, true);

    // 准备 SQL 语句
    // 使用 REPLACE INTO 覆盖数据
    $sql = "REPLACE INTO $table (id, onOff, tel, videoUrl, title, videoTitles, topicContent, questionAnswer, correctAnswerOption, telNumber, teacherSName, teacherTag, profile, other)
            VALUES (:id, :onOff, :tel, :videoUrl, :title, :videoTitles, :topicContent, :questionAnswer, :correctAnswerOption, :telNumber, :teacherSName, :teacherTag, :profile, :other)";
    
    $stmt = $pdo->prepare($sql);

    // 绑定参数并执行
    $stmt->execute([
        'id' => 1,  // 假设覆盖的是 id 为 1 的行，您可以根据实际情况修改
        'onOff' => $data['onOff'],
        'tel' => $data['tel'],
        'videoUrl' => $data['videoUrl'],
        'title' => $data['title'],
        'videoTitles' => json_encode($data['videoTitles'], JSON_UNESCAPED_UNICODE),
        'topicContent' => $data['topicContent'],
        'questionAnswer' => json_encode($data['questionAnswer'], JSON_UNESCAPED_UNICODE),
        'correctAnswerOption' => $data['correctAnswerOption'],
        'telNumber' => $data['telNumber'],
        'teacherSName' => $data['teacherSName'],
        'teacherTag' => json_encode($data['teacherTag'], JSON_UNESCAPED_UNICODE),
        'profile' => $data['profile'],
        'other' => $data['other'],
    ]);

    // 返回成功消息
    http_response_code(200);
    echo "200";
    exit;
}

// 处理 GET 请求，读取数据库中的数据并返回
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // 准备 SQL 语句
    $sql = "SELECT * FROM $table ORDER BY id DESC LIMIT 1";
    $stmt = $pdo->query($sql);
    
    // 获取数据
    $data = $stmt->fetch();
    
    if ($data) {
        // 对需要反序列化的字段进行反序列化
        $data['videoTitles'] = json_decode($data['videoTitles'], true);
        $data['questionAnswer'] = json_decode($data['questionAnswer'], true);
        $data['teacherTag'] = json_decode($data['teacherTag'], true);

        // 设置响应头
        header('Content-Type: application/json');
        // 返回数据
        http_response_code(200);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        // 数据不存在时返回错误消息
        http_response_code(404);
        echo "API data not found.";
    }
    exit;
}

// 处理其他类型的请求
http_response_code(405);
echo "Method Not Allowed.";

?>
